package com.example.gobang.api;

import com.example.gobang.model.User;
import com.example.gobang.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.soap.Addressing;

@RestController
public class UseApi {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest request){
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return null;
        }
        User user = userMapper.selectByName(username);
        if(user==null||!user.getPassword().equals(password)){
            return null;
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        return user;
    }
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return null;
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insertSellect(user);
        return user;
    }
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
     try{
         HttpSession httpSession = request.getSession(false);
         User user = (User) httpSession.getAttribute("user");
         User newUser = userMapper.selectByName(user.getUsername());
         return newUser;
     }catch (NullPointerException e){
         return new User();
     }
    }
}
